package cn.cvs.controller;

import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.sysRole.SysRoleService;
import cn.cvs.service.sysUser.SysUserService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.PageSupport;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;

/**
 * @author 许欣
 * 时间：2022/4/29 15:00
 * 描述：
 */
@Controller
@RequestMapping(value = "/user")
public class SysUserController {
    private Logger logger=Logger.getLogger(SysUserController.class);
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;
    @RequestMapping(value = "/toLogin")
    public String login(){
        return "login";
    }

    //登录
    @RequestMapping(value = "/login")
    public String doLogin(@RequestParam String account, @RequestParam String password,
                          HttpServletRequest request, HttpSession session, HttpServletResponse response) throws Exception {
        SysUser loginUser=sysUserService.login(account,password);
        if (loginUser!=null){
            //登录成功
            session.setAttribute(Constants.USER_SESSION,loginUser);
            return "redirect:/user/toMain";
        }else {
            request.setAttribute("error","用户名或密码不正确");
            return "redirect:/user/login";
        }
    }
    //跳转到首页
    @RequestMapping(value = "/toMain")
    public String main(HttpSession session){
        if (session.getAttribute(Constants.USER_SESSION)==null){
            return "redirect:/user/toMain";
        }
        return "frame";
    }
    //一个抛出异常的接口
    @RequestMapping("/exLogin")
    public String exLogin(@RequestParam String account, @RequestParam String password) throws Exception {
        SysUser user=sysUserService.login(account,password);
        if (user==null){
            //登录失败
            throw  new RuntimeException("用户名或密码错误");
        }
        return "redirect:/user/toMain";
    }
    @RequestMapping("/list")
    public String getUserList(Model model,String queryRealName,Integer queryRoleId,@RequestParam(defaultValue = "1")Integer pageIndex) throws Exception {
        List<SysUser>userList=null;
        try {
            //设置页面容量
            int pageSize = Constants.pageSize;
            //总数量
            int totalCount = sysUserService.getUserCount(queryRealName, queryRoleId);
            //总页数
            PageSupport pageSupport = new PageSupport();
            pageSupport.setCurrentPageNo(pageIndex);
            pageSupport.setPageSize(pageSize);
            pageSupport.setTotalCount(totalCount);
            int totalPageCount = pageSupport.getTotalPageCount();
            //控制首页和尾页
            if (pageIndex > totalPageCount) {
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            userList = sysUserService.getUserList(queryRealName, queryRoleId, pageIndex, pageSize);
            model.addAttribute("userList", userList);
            List<SysRole> roleList = null;
            roleList = sysRoleService.getRoleList();
            model.addAttribute("roleList", roleList);
            model.addAttribute("queryRealName", queryRealName);
            model.addAttribute("queryRoleId", queryRoleId);
            model.addAttribute("totalPageCount", totalPageCount);
            model.addAttribute("totalCount", totalCount);
            model.addAttribute("pageIndex", pageIndex);
        }catch (Exception e){
            e.printStackTrace();
//            return "redirect:/user/toSysError";
        }
        return "/sysUser/list";
    }
    //跳转到异常处理页面
    @RequestMapping(value = "/toSysError")
    public String toSysError(){
        return "sysError";
    }
    //跳到添加页面
    @RequestMapping("/toAdd")
    public String toAdd(){
        return "sysUser/add";
    }
    @RequestMapping("/add")
    public String add(@Valid SysUser sysUser) throws Exception {
        sysUserService.add(sysUser);
        return "redirect:/user/list";

    }
    //查询用户详情
    @GetMapping("/view/{id}")
    public String view(@PathVariable Integer id,Model model) throws Exception {
        SysUser sysUser=sysUserService.getUserById(id);
        model.addAttribute(sysUser);//传值
        return "sysUser/view";
    }
    //跳转修改
    @RequestMapping("/toUpdate")
    public String toUpdate(@RequestParam Integer uid,Model model) throws Exception {
        SysUser sysUser=sysUserService.getUserById(uid);
        model.addAttribute(sysUser);
        return "sysUser/update";
    }
    //修改
    @RequestMapping("/update")
    public String update(SysUser sysUser,HttpSession session) throws Exception {
//        sysUser.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
//        if (sysUserService.update(sysUser)){
//            return "redirect:/user/list";
//        }
//        return "sysUser/update";
        sysUserService.update(sysUser);
        return "redirect:/user/list";
    }
  @ResponseBody
    @GetMapping("/userExist")
    public Object userExist(@RequestParam String account) throws Exception {
        logger.debug("验证用户名account="+account+"的用户名是否存在");
      HashMap<String,Object>map=new HashMap<>();
      if (StringUtils.isNullOrEmpty(account)){
          map.put("exist",1);
      }else {
          SysUser sysUser=sysUserService.getByAccount(account);
          if (null!=sysUser){
              map.put("exist",1);
          }else {
              map.put("exist",0);
          }
      }
      return JSON.toJSONString(map);
  }
  //删除
    @RequestMapping("/del/{id}")
    public String del(@PathVariable Integer id) throws Exception {
        System.out.println(id);
        sysUserService.deleteById(id);
        return "redirect:/user/list";//进入controller
    }
    //根据id获取
    @RequestMapping(value = "/byId")
    public String byId(@PathVariable Integer id,Model model) throws Exception {
        SysUser sysUser= sysUserService.getUserById(id);
        model.addAttribute("sysUser",sysUser);
        return "/sysUser/add";
    }

    //退出
    @RequestMapping(value = "/logout")
    public String logout(HttpSession session){
        session.invalidate();//清空数据
        return "redirect:/";
    }

}
